import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from .serializers import WeChatLoginSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from .models import LLMChatLog
from .serializers import ChatSerializer
from .prompts import SYSTEM_PROMPT
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.decorators import action

class LocalModelAPI(APIView):
    """
    本地大模型调用代理接口
    """

    def post(self, request):
        serializer = ChatSerializer(data=request.data)
        if serializer.is_valid():
            # 调用本地模型服务（假设地址为 http://localhost:5000/generate）
            try:
                # 使用从单独文件导入的系统提示词
                user_prompt = serializer.validated_data['prompt']
                combined_prompt = f"{SYSTEM_PROMPT}\n\n用户问题：{user_prompt}"
                
                resp = requests.post(
                    "http://localhost:5000/generate",
                    json={"prompt": combined_prompt},
                    timeout=30
                )
                result = resp.json()

                # 保存交互记录
                LLMChatLog.objects.create(
                    user=request.user,
                    prompt=serializer.validated_data['prompt'],
                    response=result['response']
                )
                return Response(result, status=status.HTTP_200_OK)

            except Exception as e:
                return Response({"error": str(e)}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class WeChatLoginView(APIView):
    permission_classes = [AllowAny]
    @swagger_auto_schema(
        tags=['create'],
        operation_summary='微信小程序登录',
        operation_description='''### 接口说明
用于微信小程序端用户登录认证，获取访问令牌

#### 前置条件
1. 小程序已通过微信开放平台认证
2. 已在settings.py配置WECHAT_APP_ID和WECHAT_APP_SECRET

#### 处理流程
1. 接收小程序端发送的临时code
2. 调用微信接口换取openid
3. 自动创建或关联本地用户
4. 生成JWT访问令牌返回''',
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['code'],
            properties={
                'code': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='''### 参数说明
- 来源：通过微信小程序wx.login()接口获取
- 格式：32位字符串
- 有效期：5分钟
- 示例：'08123456789ABCDEF0123456789ABCDEF' ''',
                    example='08123456789ABCDEF0123456789ABCDEF'
                )
            }
        ),
        responses={
            200: openapi.Response(
                description='''### 成功响应
返回JWT令牌对，access_token用于API授权，refresh_token用于令牌刷新''',
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'access': openapi.Schema(
                            type=openapi.TYPE_STRING,
                            description='访问令牌，有效期1小时',
                            example='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...'
                        ),
                        'refresh': openapi.Schema(
                            type=openapi.TYPE_STRING,
                            description='刷新令牌，有效期7天',
                            example='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...'
                        )
                    }
                )
            ),
            400: openapi.Response(
                description='参数错误或微信登录验证失败',
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'detail': openapi.Schema(
                            type=openapi.TYPE_STRING,
                            description='错误提示信息',
                            example='微信登录失败: invalid code'
                        )
                    }
                )
            )
        }
    )
    def post(self, request):
        serializer = WeChatLoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            refresh = RefreshToken.for_user(user)
            return Response({
                'refresh': str(refresh),
                'access': str(refresh.access_token),
            }, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
from .serializers import ChatSerializer